﻿/*
Description:基于jQuery EasyUI常用方法扩展及通用功能集合
Date:2015-07-29
*/

/*
快速获取选中的列值,返回Json数据
*/
function fnSelected(rows, columns) {
    var jsonData = [];
    // 使用 for 循环遍历 rows
    for (var i = 0; i < rows.length; i++) {
        var row = rows[i];
        var rowData = {};
        // 使用 for 循环遍历 columns
        for (var j = 0; j < columns.length; j++) {
            var column = columns[j];
            var columnName = column.field; // 列名
            var columnValue = row[columnName]; // 对应的值
            rowData[columnName] = columnValue; // 将列名和对应的值保存到对象中
        }

        jsonData.push(rowData); // 将当前行的数据对象添加到数组中
    }
    return jsonData;
}

/*
批量返回 所有选中的列值,返回集合数据
*/
function fnSelectList(datagrID, selectedRows) {
    var jsonData = [];
    for (var i = 0; i < selectedRows.length; i++) {
        var rowData = selectedRows[i];
        var keyValuePair = {};
        // 遍历所有列获取field和值
        var columns = $('#' + datagrID).datagrid('getColumnFields', true).concat($('#' + datagrID).datagrid('getColumnFields', false));
        for (var j = 0; j < columns.length; j++) {
            var field = columns[j];
            keyValuePair[field] = rowData[field];
        }

        jsonData.push(keyValuePair);
    }
    return jsonData;
}

//随机数
function GetRand() {
    var sRand = "";
    for (var i = 0; i < 10; i++) {
        sRand = sRand + (parseInt(Math.random() * 9)).toString();
    }
    return sRand;
}
$.extend($.fn.datagrid.methods, {
    /**
     * 增加空行 用于没有数据或者数据不足以填满整个列表
     * @param jq datagrid对象
     */
    fillRows: function (jq) {
        var grid = $(jq);
        var pageopt = grid.datagrid('getPager').data("pagination").options;
        var pageSize = pageopt.pageSize;
        var datacounts = pageopt.pageSize - 1;//填充总数
        var rows = grid.datagrid("getRows");
        var length = rows.length;

        if (pageSize >= datacounts && length < datacounts) {
            var options = grid.datagrid("options");
            var gpanel = grid.datagrid("getPanel");
            var gbody1 = gpanel.find(".datagrid-view1 .datagrid-body");
            var tbody1 = gbody1.find("table>tbody");
            var gbody2 = gpanel.find(".datagrid-view2 .datagrid-body");
            var tbody2 = gbody2.find("table>tbody");

            var column1s = grid.datagrid("getColumnFields", true);
            var column2s = grid.datagrid("getColumnFields");
            var td1s = "";
            var td2s = "";
            if (tbody1.length > 0) {
                td1s += options.rownumbers ? "<td class='datagrid-td-rownumber'><div class=\"datagrid-cell-rownumber\"></div></td>" : "";

                if (column1s.length > 0) {
                    $.each(column1s, function (i, field) {
                        var opt = grid.datagrid("getColumnOption", field);
                        if (opt != null && !opt.hidden) {
                            if (opt.checkbox) {
                                td1s += "<td field=\"" + field + "\"><div class=\"datagrid-cell-check\"></div></td>";
                            } else {
                                td1s += "<td field=\"" + field + "\"><div class=\"datagrid-cell datagrid-cell-c1-" + field + "\"></div></td>";
                            }
                        }
                    });
                }
                var events = $._data(gbody1.children().get(0), 'events');
                if (events != null) {
                    //重新绑定click、dblclick事件
                    var clickfunc = events.click[0].handler;
                    events.click[0].handler = function (e) {
                        var tt = $(e.target);
                        var tr = tt.closest("tr.datagrid-row");
                        if (tr.hasClass("datagrid-blank-row")) {
                            return;
                        }
                        clickfunc(e);
                    };
                    var dblclickfunc = events.dblclick[0].handler;
                    events.dblclick[0].handler = function (e) {
                        var tt = $(e.target);
                        var tr = tt.closest("tr.datagrid-row");
                        if (tr.hasClass("datagrid-blank-row")) {
                            return;
                        }
                        dblclickfunc(e);
                    };
                }
            }
            if (tbody2.length > 0 && column2s.length > 0) {
                $.each(column2s, function (i, field) {
                    var opt = grid.datagrid("getColumnOption", field);
                    if (opt != null && !opt.hidden) {
                        if (opt.checkbox) {
                            td2s += "<td field=\"" + field + "\"><div class=\"datagrid-cell-check\"></div></td>";
                        } else {
                            td2s += "<td field=\"" + field + "\"><div class=\"datagrid-cell datagrid-cell-c1-" + field + "\"></div></td>";
                        }
                    }
                });

                var events = $._data(gbody2.get(0), 'events');
                if (events != null) {
                    //重新绑定click、dblclick事件
                    var clickfunc = events.click[0].handler;
                    events.click[0].handler = function (e) {
                        var tt = $(e.target);
                        var tr = tt.closest("tr.datagrid-row");
                        if (tr.hasClass("datagrid-blank-row")) {
                            return;
                        }
                        clickfunc(e);
                    };
                    var dblclickfunc = events.dblclick[0].handler;
                    events.dblclick[0].handler = function (e) {
                        var tt = $(e.target);
                        var tr = tt.closest("tr.datagrid-row");
                        if (tr.hasClass("datagrid-blank-row")) {
                            return;
                        }
                        dblclickfunc(e);
                    };
                }
            }
            for (var i = length; i < datacounts; i++) {
                if (td1s != "") {
                    var tr = '<tr class="datagrid-blank-row datagrid-row'
                        + (options.striped && i % 2 != 0 ? ' datagrid-row-alt' : '') + '">' + td1s + '</tr>';
                    $(tr).appendTo(tbody1);
                }
                if (td2s != "") {
                    var tr = '<tr class="datagrid-blank-row datagrid-row'
                        + (options.striped && i % 2 != 0 ? ' datagrid-row-alt' : '') + '">' + td2s + '</tr>';
                    $(tr).appendTo(tbody2);
                }
            }
        }
    }
});

function Request(paras) {
    var url = location.href;   //url
    var paraString = url.substring(url.indexOf("?") + 1, url.length).split("&");
    var paraObj = {}   //参数组
    for (i = 0; j = paraString[i]; i++) {
        paraObj[j.substring(0, j.indexOf("=")).toLowerCase()] = j.substring(j.indexOf("=") + 1, j.length);
    }
    var returnValue = paraObj[paras.toLowerCase()];
    if (typeof (returnValue) == "undefined") {
        return "";
    } else {
        return returnValue;
    }
}

//创建模拟窗口
function OpenWindow(title, url, width, height, callback) {
    var jq = top.jQuery; //父窗口jQuery对象
    var _w = 500; if (width) _w = width;
    var _h = 300; if (height) _h = height;
    var $win = jq('#mPopWin').window({
        title: title,
        width: _w,
        height: _h,
        modal: true,
        minimizable: false,
        top: (jq(window).height() - _h) * 0.5 + 50,
        left: (jq(window).width() - _w) * 0.5 + 50,
        //top: (jq(window).height() - _h + 50) * 0.5,
        //left: (jq(window).width() - _w) * 0.5,
        loadingMessage: "正在加载数据",
        onBeforeOpen: function () {
            jq('#mPopWin iframe').remove();
            //jq('#mPopWin').addClass("easyui-window");
            jq("<iframe frameborder=\"0\" src='" + url + "' style=\"width: 100%; height: 100%; overflow: auto;\"></iframe>").appendTo(jq('#mPopWin'));
        },
        onBeforeClose: function () {
            if (callback) {
                callback.call();
            }
        },
        onClose: function () {
            jq('#mPopWin iframe').remove();
        }
    });
    $win.window('open');
}

//创建子模拟窗口
function OpenSubWindow(title, url, width, height, callback) {
    var jq = top.jQuery; //获取父窗口jQuery对象
    var _w = 500; if (width) _w = width;
    var _h = 300; if (height) _h = height;
    var $win = jq('#cPopWin').window({
        title: title,
        width: _w,
        height: _h,
        modal: true,
        minimizable: false,
        top: (jq(window).height() - _h) * 0.5 + 20,
        left: (jq(window).width() - _w) * 0.5 + 20,
        //top: (jq(window).height() - _h + 180) * 0.5,
        //left: (jq(window).width() - _w + 618) * 0.5,
        loadingMessage: "正在加载数据",
        onBeforeOpen: function () {
            jq('#cPopWin iframe').remove();
            jq("<iframe frameborder=\"0\" src='" + url + "' style=\"width: 100%; height: 100%; overflow: auto;\"></iframe>").appendTo(jq('#cPopWin'));
        },
        onBeforeClose: function () {
            if (callback) {
                callback.call();
            }
        },
        onClose: function () {
            jq('#cPopWin iframe').remove();
        }
    });
    $win.window('open');
}

/*加载数据提示*/
//function ajaxLoading() {
//    $("<div class=\"datagrid-mask\"><iframe id=\"iframe1\" src=\"about:blank\" frameBorder=\"0\" marginHeight=\"0\" marginWidth=\"0\" style=\"position:absolute; visibility:inherit; top:0px;left:0px;width:100%; height:100%;z-index:-1; filter:alpha(opacity=0.5);\"></iframe></div>").css({ "display": "block", "z-index": "999999" }).appendTo("body");
//    $("<div class=\"datagrid-mask-msg\"></div>").html("LoadIng......").appendTo("body").css({ "display": "block", "left": ($(document.body).outerWidth(true) - 190) / 2, "top": ($(window).height() - 200) / 2 });
//}
/* 加载数据提示 - 使用 icon-Loading 样式 */
function ajaxLoading() {
    // 创建遮罩层
    $("<div class=\"datagrid-mask\"><iframe id=\"iframe1\" src=\"about:blank\" frameBorder=\"0\" marginHeight=\"0\" marginWidth=\"0\" style=\"position:absolute; visibility:inherit; top:0px;left:0px;width:100%; height:100%;z-index:-1; filter:alpha(opacity=0.5);\"></iframe></div>")
        .css({ "display": "block", "z-index": "999999" })
        .appendTo("body");

    // 创建加载动画（使用 icon-Loading 样式）
    $("<div class=\"datagrid-mask-msg\"></div>")
        .html('<i class="icon-Loading"></i> Loading...')
        .appendTo("body")
        .css({
            "display": "flex",
            "align-items": "center",
            "justify-content": "center",
            "left": ($(document.body).outerWidth(true) - 190) / 2,
            "top": ($(window).height() - 200) / 2,
            "font-size": "16px",
            "padding": "15px 20px",
            "background": "rgba(0, 0, 0, 0.7)",
            "color": "#fff",
            "border-radius": "4px"
        });
}
/*去掉加载数据提示*/
function ajaxLoadEnd() {
    $(".datagrid-mask").remove();
    $(".datagrid-mask-msg").remove();
}
function OpenSubSubWindow(title, url, width, height, callback) {
    var jq = top.jQuery; //获取父窗口jQuery对象
    var _w = 500; if (width) _w = width;
    var _h = 300; if (height) _h = height;
    var $win = jq('#tPopWin').window({
        title: title,
        width: _w,
        height: _h,
        modal: true,
        minimizable: false,
        top: (jq(window).height() - _h) * 0.5 + 20,
        left: (jq(window).width() - _w) * 0.5 + 20,
        loadingMessage: "正在加载数据",
        onBeforeOpen: function () {
            jq('#tPopWin iframe').remove();
            jq("<iframe frameborder=\"0\" src='" + url + "' style=\"width: 100%; height: 100%; overflow: auto;\"></iframe>").appendTo(jq('#tPopWin'));
        },
        onBeforeClose: function () {
            if (callback) {
                callback.call();
            }
        },
        onClose: function () {
            jq('#tPopWin iframe').remove();
        }
    });
    $win.window('open');
}

//打开标签窗口
//function addTab(title, href, fnCallBack) {
//    var tt = top.jQuery('#tabs');
//    if (tt.tabs('exists', title)) {//如果tab已经存在,则选中并刷新该tab
//        tt.tabs('select', title);

//    }
//    else {
//        //var h = document.body.clientHeight - 40;
//        var h = document.body.clientHeight;
//        var content = "<div style='height:" + h + "px;'><iframe frameborder=\"0\" src=\"" + href + "\" style=\"width:100%; height:" + h + "px; overflow:auto;\"></iframe></div>";
//        tt.tabs('add', {
//            title: title,
//            closable: true,
//            content: content,
//            iconCls: 'icon-edit'
//        });
//        tt.tabs({
//            onClose: function (tt) {
//                if (fnCallBack) {
//                    fnCallBack.call();
//                }
//            }
//        });
//    }
//    tt.tabs('select', title);
//}

//关闭Tab打开的页面
function closeTab(title) {
    var jq = parent.jQuery;
    jq('#tabs').tabs('close', title);
}

//关闭Tab窗口且右下角有消息提示
function closeTabAfterNotice(msg, tabTitle) {
    Notice(msg);
    if (msg.indexOf('失败') == -1)
        closeTab(tabTitle);
    return false;
}

//关闭模拟窗口
function CloseWindow() {
    var jq = top.jQuery; //父窗口jQuery对象
    jq('#mPopWin').window("close");
}
//打开进度条
function MessagerProgress(msg) {
    var jq = top.jQuery; //父窗口jQuery对象
    jq.messager.progress({
        title: '提示',
        msg: msg,
        text: ''
    });
}
//关闭进度条
function MessagerProClose() {
    var jq = top.jQuery; //父窗口jQuery对象PostJson
    jq.messager.progress('close');
}
//关闭窗口且右下角有消息提示
function CloseWindowAfterNotice(msg) {
    Notice(msg);
    if (msg.indexOf('失败') == -1)
        CloseWindow();
    return false;
}
//关闭子模拟窗口
function CloseSubWindow() {
    var jq = top.jQuery; //父窗口jQuery对象
    jq('#cPopWin').window("close");
}
function CloseSubSubWindow() {
    var jq = top.jQuery; //父窗口jQuery对象
    jq('#tPopWin').window("close");
}

//关闭子窗口且右下角有消息提示
function CloseSubWindowAfterNotice(msg) {
    Notice(msg);
    if (msg.indexOf('失败') == -1)
        CloseSubWindow();
    return false;
}
function CloseSubSubWindowAfterNotice(msg) {
    Notice(msg);
    if (msg.indexOf('失败') == -1)
        CloseSubSubWindow();
    return false;
}
//关闭窗口且右下角有消息提示
function CloseWindowNotice(msg) {
    Notice(msg);
    if (msg.indexOf('失败') == -1)
        CloseWindow();
    return false;
}

//控制class为checkNum的文本框只能输入数字。
function checkNumber() {
    $(".checkNum").keypress(function (event) {
        event = (event) ? event : ((window.event) ? window.event : "");
        var keyCode = event.keyCode ? event.keyCode : event.which;
        if (keyCode == 8 || keyCode == 45 || keyCode == 46) return true;
        else if (keyCode >= 48 && keyCode <= 57) return true;
        else return false;
    }).focus(function () {
        this.style.imeMode = 'disabled';
    });
}

//控制class为checkNum的文本框只能输入数字（不可输入负数）
function checkInt() {
    $(".checkInt").keypress(function (event) {
        event = (event) ? event : ((window.event) ? window.event : "");
        var keyCode = event.keyCode ? event.keyCode : event.which;
        if (keyCode == 8 || keyCode == 46) return true;
        else if (keyCode >= 48 && keyCode <= 57) return true;
        else return false;
    }).focus(function () {
        this.style.imeMode = 'disabled';
    });
}

//对话确认框
//调用：return Confirm('确认？')
function Confirm(msg, callbck) {
    var jq = top.jQuery; //父窗口jQuery对象
    jq.messager.confirm('确认', msg, function (r) {
        if (r) {
            callbck();
        }
    });
    return false;
}

//提示
function Alert(msg) {
    var jq = top.jQuery; //父窗口jQuery对象
    jq.messager.alert("提示", msg, "info");
    return false;
}
//中 右提示框
function centerRight(msg) {
    var jq = top.jQuery; //父窗口jQuery对象
    jq.messager.show({
        title: '消息',
        msg: msg,
        showType: 'fade',
        style: {
            left: '',
            right: 0,
            bottom: ''
        }
    });
    return false;
}

//异常
function Error(msg) {
    //var jq = top.jQuery; //父窗口jQuery对象
    //jq.messager.alert("异常提示", msg, "error");
    //return false;
}

//疑问
function Question(msg) {
    var jq = top.jQuery; //父窗口jQuery对象
    jq.messager.alert("确认提示", msg, "question");
    return false;
}

//警告
function Warning(msg) {
    var jq = top.jQuery; //父窗口jQuery对象
    jq.messager.alert("警告", msg, "warning");
    return false;
}

//消息提示,显示3秒
function Notice(msg) {
    var jq = top.jQuery; //父窗口jQuery对象
    jq.messager.show({ title: "消息提醒", msg: msg, timeout: 3000, showType: 'slide' });
    return false;
}

//个人消息提醒
function MessageRemind(msg) {
    var jq = top.jQuery; //父窗口jQuery对象
    jq.messager.show({ title: "消息提醒", msg: msg, timeout: 3000, width: 350, height: 200 });
    return false;
}

//获取DataGrid选中行的字段值
function GetDataGridSelectedRow(tblID, columnField) {
    var ss = [];
    var $dg = $('#' + tblID);//获取数据源
    var rows = $dg.datagrid('getSelections');
    for (var i = 0; i < rows.length; i++) {
        var row = rows[i];
        ss.push(row[columnField]);
    }
    if (ss.length == 0) return "";
    $dg.datagrid('clearSelections');
    return ss.join(",");
}

//Checkbox 全选
function fnSelectAll(obj, targetID) {
    var isChked = $(obj).attr("checked") == "checked";
    if (isChked)
        $("#" + targetID).find("input[type='checkbox']").attr("checked", "checked");
    else
        $("#" + targetID).find("input[type='checkbox']").removeAttr("checked");
}
var DataService = {
    AjaxGet: function (url, callback, isAsync) {
        ajaxLoading();
        if (typeof (isAsync) == "undefined")
            isAsync = true;
        $.ajax({
            type: "get",
            async: isAsync,
            url: url,
            contentType: "application/x-www-form-urlencoded; charset=UTF-8",
            success: function (data, textStatus) {
                callback(data);
            }
        });
        ajaxLoadEnd();
    },
    AjaxPost: function (url, arrData, callback) {
        ajaxLoading();
        $.ajax({
            type: "post",
            url: url,
            data: arrData,
            contentType: "application/x-www-form-urlencoded; charset=UTF-8",
            success: function (data, textStatus) {
                callback(data);
            }
        });
        ajaxLoadEnd();
    },
    GetExcelFile: function (url, callback) {
        ajaxLoading();
        let xhr = new XMLHttpRequest();
        xhr.open("GET", url, true);
        xhr.responseType = 'blob'; // 指定响应类型为Blob

        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    // 成功获取文件
                    const blob = xhr.response;
                    callback(true, { blob });
                    ajaxLoadEnd();
                } else {
                    // 请求失败
                    let errorMsg = "错误代码: " + xhr.status;
                    try {
                        // 尝试解析错误信息（可能是JSON）
                        const errorResponse = JSON.parse(xhr.responseText);
                        errorMsg += " - " + (errorResponse.message || xhr.responseText);
                    } catch (e) {
                        errorMsg += " - " + xhr.responseText;
                    }
                    callback(false, errorMsg);
                    ajaxLoadEnd();
                }
            }
        };

        xhr.send();
    },
    PostJson: function (url, data, callback) {
        ajaxLoading();
        let xhr = new XMLHttpRequest();
        xhr.open("POST", url, true);
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    ajaxLoadEnd();
                    var responseText = xhr.responseText;
                    if (!responseText || responseText.trim() === "") {
                        return callback(true, null);  // 空响应视为成功但无数据
                    }
                    var data = JSON.parse(responseText);
                    callback(true, data);
                } else {
                    ajaxLoadEnd();
                    // 请求失败，调用回调函数并传入错误信息
                    callback(false, "错误代码:," + xhr.status + xhr.responseText);
                }
            }
        };
        xhr.send(JSON.stringify(data)); // 将数据转换为 JSON 字符串
    },
    PostNotJson: function (url, data, callback) {
        ajaxLoading();
        let xhr = new XMLHttpRequest();
        xhr.open("POST", url, true);
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    // 请求成功，调用回调函数并传入响应数据
                    callback(true, xhr.responseText);
                    ajaxLoadEnd();
                } else {
                    // 请求失败，调用回调函数并传入错误信息
                    callback(false, "错误代码:," + xhr.status + xhr.responseText);
                    ajaxLoadEnd();
                }
            }
        };
        xhr.send(JSON.stringify(data)); // 将数据转换为 JSON 字符串
    }
};

var Translation = {
    PageLanguage: function (url, data, callback) {
        ajaxLoading();
        let xhr = new XMLHttpRequest();
        xhr.open("POST", url, true);
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    // 请求成功，调用回调函数并传入响应数据
                    callback(true, JSON.parse(xhr.responseText));
                    ajaxLoadEnd();
                } else {
                    // 请求失败，调用回调函数并传入错误信息
                    callback(false, null);
                    ajaxLoadEnd();
                }
            }
        };
        xhr.send(JSON.stringify(data)); // 将数据转换为 JSON 字符串
    }
}
//日期比较
function DateDiff(sDate, eDate) {
    var arr = sDate.split("-");
    var startDate = new Date(arr[0], arr[1], arr[2]);
    var startTimes = startDate.getTime();

    var arr2 = eDate.split("-");
    var endDate = new Date(arr2[0], arr2[1], arr2[2]);
    var endTimes = endDate.getTime();

    return startTimes - endTimes;
}

//格式化日期
$.FormatDateTime = function (obj, isShort) {
    var arr = obj.split(' ');
    if (arr.length > 0) return arr[0];
    else return obj;
}

// 格式化金额
$.FormatMoney = function ($cell) {
    var reg = /[\$,%]/g;
    var key = parseFloat(String($cell).replace(reg, '')).toFixed(2);
    return isNaN(key) ? 0.00 : key;
}

function CurentDate() {
    var now = new Date();
    var year = now.getFullYear();       //年
    var month = now.getMonth() + 1;     //月
    var day = now.getDate();            //日
    return year + "-" + month + "-" + day;
}

//格式化时间
function FormatDateTime(obj, IsMi) {
    return obj;
}

/**********区域打印********/
function PrintScope() {
    var bdhtml = window.document.body.innerHTML; //获取当前页的html代码
    var sprnstr = "<!--start print-->"; //设置打印开始区域
    var eprnstr = "<!--end print-->"; //设置打印结束区域
    var prnhtml = bdhtml.substring(bdhtml.indexOf(sprnstr) + 18);
    prnhtml = prnhtml.substring(0, prnhtml.indexOf(eprnstr));
    window.document.body.innerHTML = prnhtml;
    window.print();
    window.document.body.innerHTML = bdhtml;
}
/********End*********/

function closeWindow() {
    window.opener = null;
    window.open('', '_self');
    window.close();
}

//lhgdialog弹窗
function fnWinOpen(options) {
    var defaults = { "width": 600, "height": 400, "title": "", "url": "" };
    var opt = $.extend(defaults, options);
    $.dialog({
        zIndex: 99999,
        cover: true,
        width: opt.width,
        height: opt.height,
        max: false,
        min: false,
        title: opt.title,
        content: "url:" + opt.url + ""
    });
    return false;
}

//lhgdialog弹窗
function fnWindowsOpen(options) {
    var defaults = { "width": 600, "height": 400, "title": "", "url": "" };
    var opt = $.extend(defaults, options);
    $.dialog({
        zIndex: 99999,
        cover: false,
        width: opt.width,
        height: opt.height,
        max: true,
        min: true,
        title: opt.title,
        content: "url:" + opt.url + ""
    });
    return false;
}

function fnWinClose() {
    var api = frameElement.api,
        W = api.opener;
    api.close();
}

function GetCookie(name) {
    //获取当前所有cookie
    var strCookies = document.cookie;
    //截取变成cookie数组
    var array = strCookies.split(';');
    //循环每个cookie
    for (var i = 0; i < array.length; i++) {
        //将cookie截取成两部分
        var item = array[i].split("=");
        //判断cookie的name 是否相等
        if (item[0] == name) {
            return item[1];
        }
    }
    return null;
}

function GetCookieUser() {
    //获取当前所有cookie
    var strCookies = document.cookie;
    //截取变成cookie数组
    var array = strCookies.split(';');
    //循环每个cookie
    for (var i = 0; i < array.length; i++) {
        //将cookie截取成两部分
        var item = array[i].split("=");
        //判断cookie的name 是否相等
        if (item[0].indexOf("MES_USER_LOGIN_CookieName") >= 0) {
            return item[1];
        }
    }
    return null;
}

/*
execl导出函数,参数  datagridID,导出名
*/
function ToExcel(datagridId, data) {
    // 假设你的datagrid已经初始化完成，并且你知道它的loader，field等信息
    var datagridOptions = $('#' + datagridId).datagrid('getPanel').panel('options');
    var columns = datagridOptions.columns;
    // 获取列标题，并过滤掉 checkbox 和 hidden 列
    var columnTitles = [];
    var columnFields = [];
    for (var i = 0; i < columns[0].length; i++) {
        if (columns[0][i].checkbox !== true && columns[0][i].hidden !== true) {
            columnTitles.push(columns[0][i].title);
            columnFields.push(columns[0][i].field);
        }
    }
    // 手动映射数据以确保数据正确地放置在对应的标题列中
    var mappedData = data.map(function (row) {
        var mappedRow = {};
        columnFields.forEach(function (field, index) {
            mappedRow[columnTitles[index]] = row[field];
        });
        return mappedRow;
    });
    // 将数据转换为工作表，并指定列名
    var worksheet = XLSX.utils.json_to_sheet(mappedData, { header: columnTitles });
    // 创建工作簿
    var workbook = XLSX.utils.book_new();
    // 添加工作表到工作簿
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

    // 生成 Excel 文件
    var excelBuffer = XLSX.write(workbook, {
        bookType: 'xlsx',
        type: 'array'
    });
    // 创建 Blob 对象
    var blob = new Blob([excelBuffer], { type: 'application/octet-stream' });
    // 保存文件
    saveAs(blob, fileName || 'datagrid_export.xlsx');
}

//检验表单
function validateForm() {
    var isValid = true;
    // 获取所有带有 required 属性的输入字段
    var requiredFields = document.querySelectorAll('input[required]');

    requiredFields.forEach(function (field) {
        if (field.value.trim() === '') {
            isValid = false;
            Alert(field.getAttribute('data-options').split(':')[1].replace(/'/g, '').trim() + ' 是必填项');
            field.focus();
            return;
        }
    });
    return isValid;
}